
package com.schedualnew.mq.config.aop;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Aspect
@Component
public class ControllerAspect {
    private Logger log = LoggerFactory.getLogger(ControllerAspect.class);
    private JSONObject jsonObject;

    public ControllerAspect() {
        this.jsonObject = new JSONObject();
    }

    //    @Pointcut("execution(public * com.rt.schedulenew.web.*.*(..))")
    @Pointcut("execution(public * com.schedualnew.mq..*Controller.*(..))")
    private void controllerAspect() {

    }

    @Around("controllerAspect()")
    public Object methodAround(ProceedingJoinPoint joinPoint) throws Throwable {
        // long startTimeMillis = MillisecondClock.getInstance().now();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        //序列化时过滤掉request和response
        List<Object> filterArgs = Arrays.stream(args)
                .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse)))
                .collect(Collectors.toList());

        if (methodName.contains("patch")) {
            log.info("【" + methodName + "】请求内容：{}", (args.length > 0) ? args[0].toString() : "null");
        } else {
            String string = "【" + methodName + "】请求内容：{}";
            String jsonString;
            if (filterArgs.size() > 0) {
                if (filterArgs.get(0) instanceof MultipartFile) {
                    MultipartFile arg = (MultipartFile) filterArgs.get(0);
                    Map<String, String> map = new HashMap<>();
                    map.put("filename", arg.getOriginalFilename());
                    jsonString = JSONObject.toJSONString(map);
                } else {
                    jsonString = JSONObject.toJSONString(filterArgs.get(0));
                }
            } else {
                jsonString = "null";
            }
            log.info(string, jsonString);
        }
        Object result = joinPoint.proceed();
        String string2 = "【" + methodName + "】响应内容：{}";
        log.info(string2, JSONObject.toJSONString(result));
        //log.info("【" + methodName + "】响应耗时：{}毫秒", MillisecondClock.getInstance().now() - startTimeMillis);
        return result;
    }
}
